package com.dl.exam.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dl.exam.entity.Exam;
import com.dl.exam.entity.Page;
import com.dl.exam.entity.question.Question;
import com.dl.exam.mapper.ExamMapper;
import com.dl.exam.mapper.SingleMapper;
import com.dl.exam.mapper.SubjectiveMapper;
import com.dl.exam.service.ExamService;
import com.dl.exam.util.PageUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author DL
 * @create 2022-01-30 19:01
 */
@Service
@Transactional
public class ExamServiceImpl implements ExamService {

    @Resource
    private ExamMapper examMapper;
    @Resource
    private SingleMapper singleMapper;
    @Resource
    private SubjectiveMapper subjectiveMapper;

    @Override
    public boolean startExam(String examId, String userId, Integer examType, List<String> questionIdList) {
        System.out.println("questionIdList = " + questionIdList);
        Integer examInfo = examMapper.insertExamInfo(examId, questionIdList);
        Integer examManage = examMapper.insertExamManage(examId, userId, examType);
        return examInfo != 0 && examManage != 0;
    }

    @Override
    public boolean submitExam(JSONObject jsonObject) {
        // 传过来的考试信息
        Exam exam = jsonObject.getJSONObject("exam").toJavaObject(Exam.class);
        String examId = exam.getExamId();// 考试id
        Integer examType = exam.getExamType();// 考试类型
        JSONArray answers = jsonObject.getJSONArray("answers");// 传过来的 题目id + 答案
        List<HashMap<String, Object>> listMap = null;// 用来接收从数据库查询的答案
        switch (examType){
            case 1 :
                listMap = singleMapper.queryAnswerByExamId(examId);break;
            //case 2 : singleService.getFinishedExamAnswer(examId, currentPage, 10);break;
            case 3 :
                listMap = subjectiveMapper.queryAnswerByExamId(examId);break;
        }
        //System.out.println("listMap = " + listMap);
        //System.out.println("answers = " + answers);

        List<Question> answerList = answers.toJavaList(Question.class);// 转为集合

        AtomicReference<Float> totalScore = new AtomicReference<>((float) 0);// 试卷总分
        AtomicReference<Float> userScore = new AtomicReference<>((float) 0);// 用户得分

        assert listMap != null;
        List<HashMap<String, Object>> collect = listMap.stream()// 流式操作
                .peek(map -> {
                    totalScore.set(totalScore.get() + (float) map.get("score"));// 累加每个题的分值
                }).filter(map -> {//过滤，判断用户答案是否正确
                    boolean flag = false;//是否命中; 0：未命中  >0：命中
                    for (int i = 0; i < answerList.size(); i++) {
                        if (map.get("question_id").equals(answerList.get(i).getQuestionId())) {// 使用试题id匹配题目
                            if (map.get("answer").equals(answerList.get(i).getAnswer())) {// 匹配答案
                                userScore.set(userScore.get() + (float) map.get("score"));// 累加正确题目的分值
                                flag = true;
                            }
                            answerList.remove(i);
                            //System.out.println("answerList.size() = " + answerList.size());
                            break;
                        }
                    }
                    return flag;//如果返回值为true，则将该元素交给下一个Stream流环节
                }).collect(Collectors.toList());


        System.out.println("totalScore = " + totalScore);// 试卷总分
        System.out.println("userScore = " + userScore);// 用户得分
        System.out.println("collect = " + collect);// 正确的试题

        System.out.println("answers = " + answers);
        System.out.println("answerList = " + answerList);
        // 更新考试信息表(更新答案)
        Integer examAnswer = examMapper.updateExamAnswer(examId, answers.toJavaList(Question.class));
        // 更新考试管理表
        Integer examManage = examMapper.updateExamManage(examId, userScore.get(), totalScore.get());
        return examAnswer != 0 && examManage != 0;
    }


    @Override
    public boolean updateExamManage(String userId, float score, float totalScore) {
        return examMapper.updateExamManage(userId, score, totalScore) != 0;
    }

    @Override
    public boolean updateExamAnswer(String examId, List<String> params) {
        return false;
    }

    @Override
    public Exam getUnfinishedExam(String userId) {
        return examMapper.queryUnfinishedExam(userId);
    }

    @Override
    public Page<Question> getFinishedExam(String examId, int examType, int currentPage, int pageSize) {

        PageHelper.startPage(currentPage, pageSize);
        List<Question> list = examMapper.queryFinishedExam(examId, examType);
        return (Page<Question>) PageUtils.getPage(list);
    }

    @Override
    public Page<Exam> getAllExam(String userId, int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Exam> list = examMapper.queryAllExam(userId);
        return (Page<Exam>) PageUtils.getPage(list);
    }


}
